<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Register-tbplas</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="shortcut icon" href="./img/logo.png" type="image/x-icon">
    <link rel="stylesheet" type="text/css" href="./css/element.css">
    <link rel="stylesheet" type="text/css" href="./css/index.css">
    <script src="./js/vue.js"></script>
    <script src="./js/axios.js"></script>
    <script src="./js/element.js"></script>
    <script src="./router.js"></script>
</head>

<body>
    <div id="app">
        <div class="container">
            <div class="form-header">
                <p>We kindly ask you to provide some basic information for statistics. The information will be kept
                    confidential.</p>
                <div class="scientific-decoration"></div>
            </div>

            <div class="form-content" style="padding-top: 15px;">
                <el-form ref="form" :model="form">
                    <div class="">
                        <el-form-item prop="name" label="Name"
                            :rules="[{ required: true, message: 'Given name – Middle name – Family name', trigger: ['blur', 'change'] }]">
                            <el-input v-model="form.name" placeholder="Given name – Middle name – Family name" clearable
                                :maxlength="100"></el-input>
                        </el-form-item>
                    </div>

                    <div class="">
                        <el-form-item prop="email" label="E-mail"
                            :rules="[  { required: true, message: 'xxx@yyy.com', trigger: 'blur' },
                            { type: 'email', message: 'Please enter the correct email address.', trigger: ['blur', 'change'] }]">
                            <el-input v-model="form.email" placeholder="xxx@yyy.com" clearable :maxlength="100">
                                <el-button slot="append" :disabled="isCountingDown || isSending || !form.email"
                                    @click="sendVerificationCode">
                                    {{ isCountingDown ? countdown + 's' : 'Get Code' }}
                                </el-button>
                            </el-input>
                        </el-form-item>
                    </div>

                    <div class="">
                        <el-form-item prop="verificationCode" label="Email verification code"
                            :rules="[  { required: true, message: 'Please enter the email verification code.',  trigger: ['blur', 'change']  }]">
                            <el-input v-model="form.verificationCode" placeholder="Please enter the email verification code." clearable
                                :maxlength="100"></el-input>
                        </el-form-item>
                    </div>

                    <div class="">
                        <el-form-item prop="password" label="Password"
                            :rules="[  { required: true, message: 'Please enter your account password.', trigger: ['blur', 'change'] }]">
                            <el-input v-model="form.password" placeholder="Please enter the 6-digit account password."
                                clearable :maxlength="100"></el-input>
                        </el-form-item>
                    </div>

                    <div class="">
                        <el-form-item prop="confirmPassword" label="Confirm password"
                            :rules="[  { required: true, message: 'Please enter the confirmation account password.', trigger: ['blur', 'change'] }]">
                            <el-input v-model="form.confirmPassword"
                                placeholder="Please enter your account and password again." clearable
                                :maxlength="100"></el-input>
                        </el-form-item>
                    </div>

                    <div class="">
                        <el-form-item prop="organization" label="Affiliation"
                            :rules="[ { required: true, message: 'University/Research Institute', trigger: ['blur', 'change'] },]">
                            <el-input v-model="form.organization" placeholder="University/Research Institute" clearable
                                :maxlength="100"></el-input>
                        </el-form-item>
                    </div>

                    <div class="">
                        <el-form-item prop="researchField" label="Research area"
                            :rules="[{ required: true, message: 'Condensed Matter Physics', trigger: ['blur', 'change'] },]">
                            <el-input v-model="form.researchField" placeholder="Condensed Matter Physics" clearable
                                :maxlength="100"></el-input>
                        </el-form-item>
                    </div>

                    <!-- 添加的协议确认部分 -->
                    <div class="agreement-container" :class="{ error: agreementError }">
                        <div class="agreement-content">
                            <el-checkbox v-model="form.agreementAgreed">
                                <span>I agree to the</span>
                            </el-checkbox>
                            <a class="agreement-link" @click="showAgreementDialog = true">
                                <i class="fas fa-file-contract"></i>term of use of tbplas
                            </a>
                        </div>
                        <div class="agreement-error">Please read and agree to the terms of use.</div>
                    </div>

                    <div class="submit-area">
                        <button class="submit-btn" @click.prevent="submitForm" :disabled="isSubmitting">
                            {{ isSubmitting ? 'Submitting...' : 'Submit the information and download' }}
                        </button>
                    </div>
                </el-form>
            </div>


        </div>

        <!-- 协议对话框 -->
        <el-dialog :visible.sync="showAgreementDialog" width="80%" top="5vh">
            <div class="dialog-content">
                <div class="license-header">
                    <h2>BSD License</h2>
                </div>

                <div class="license-content">
                    <div class="license-section">
                        <p>Copyright (c) 2017-2025, TBPLaS development team. All rights reserved.</p>
                    </div>

                    <div class="license-section">
                        <p>Redistribution and use in source and binary forms, with or without modification, are
                            permitted provided that the following conditions are met:</p>
                    </div>

                    <div class="license-section">
                        <p> * Redistributions of source code must retain the above copyright notice, this list of
                            conditions and
                            the following disclaimer.</p>
                        <p>* Redistributions in binary form must reproduce the above copyright notice, this list of
                            conditions
                            and the following disclaimer in the documentation and/or other materials provided with the
                            distribution.</p>
                        <p> * Neither the name of RU and WHU nor the names of its contributors may be used to endorse or
                            promote products
                            derived from this software without specific prior written permission.</p>
                    </div>

                    <div class="license-section">
                        <p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
                            OR IMPLIED WARRANTIES,
                            INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
                            PARTICULAR PURPOSE ARE
                            DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
                            INDIRECT, INCIDENTAL,
                            SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
                            SUBSTITUTE GOODS OR
                            SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
                            THEORY OF LIABILITY,
                            WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
                            IN ANY WAY OUT OF THE
                            USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</p>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="showAgreementDialog = false">close</el-button>
                <el-button type="primary" @click="agreeAndClose">Agree and Close</el-button>
            </span>
        </el-dialog>
    </div>

    <script>
        // const api = 'https://www.tbplas.net/api_tbplas_1749021606379'
        new Vue({
            el: '#app',
            data() {
                return {
                    form: {
                        name: '',
                        email: '',
                        organization: '',
                        researchField: '',
                        agreementAgreed: false,
                        password: '',
                        verificationCode: '',
                        confirmPassword: ''
                    },
                    showAgreementDialog: false,
                    agreementError: false,
                    isSubmitting: false,
                    isCountingDown: false,
                    countdown: 60,
                    countdownTimer: null,
                    isSending: false,
                };
            },
            methods: {
                sendVerificationCode() {
                    if (!this.form.email || !isValidEmail(this.form.email)) {
                        this.$notify.error({
                            title: 'Error',
                            message: 'Incorrect email address',
                            duration: 2000
                        });
                        return;
                    }
                    this.isSending = true; // 新增：控制加载态（非倒计时）
                    axios.post(`${api}/sendEmailCode`, {
                        email: this.form.email
                    }).then((response) => {
                        if (response.data.code == 200) {
                            this.$notify({
                                title: 'Success',
                                message: 'Verification code sent to your email.',
                                type: 'success',
                                duration: 2000
                            });
                            this.startCountdown(); // ✅ 成功才倒计时
                        } else {
                            this.$notify.error({
                                title: 'Failed to send',
                                message: response.data.msg,
                                duration: 2000
                            });
                            errorLog('register', response.data.msg)
                        }
                    }).catch((err) => {
                        console.log(err);
                        this.$notify.error({
                            title: 'Failed to send',
                            message: 'Could not send verification code.',
                            duration: 2000
                        });
                        errorLog('register', err)
                    }).finally(() => {
                        this.isSending = false; // 允许再次点击
                    });
                },
                startCountdown() {
                    this.isCountingDown = true;
                    this.countdown = 60;
                    this.countdownTimer = setInterval(() => {
                        this.countdown--;
                        if (this.countdown <= 0) {
                            clearInterval(this.countdownTimer);
                            this.isCountingDown = false;
                        }
                    }, 1000);
                },
                beforeDestroy() {
                    if (this.countdownTimer) {
                        clearInterval(this.countdownTimer);
                    }
                },
                submitForm() {
                    // 验证表单基本规则
                    this.$refs.form.validate((valid) => {
                        console.log(valid)
                        if (!valid) {
                            this.$notify.error({
                                title: 'fail to submit',
                                message: 'Please check and complete it.',
                                duration: 2000
                            });
                            return false;
                        }

                        // 检查协议是否同意
                        if (!this.form.agreementAgreed) {
                            this.agreementError = true;
                            this.$notify.error({
                                title: 'fail to submit',
                                message: 'Please read and agree to the usage agreement.',
                                duration: 2000
                            });
                            return false;
                        }
                        this.agreementError = false;
                        this.isSubmitting = true;
                        // 检查密码是否一致
                        if (this.form.password !== this.form.confirmPassword) {
                            this.$notify.error({
                                title: 'fail to submit',
                                message: 'The passwords do not match.',
                                duration: 2000
                            });
                            this.isSubmitting = false;
                            return false;
                        }
                        // 检查密码长度至少6为+密码必须为数字+字母组合
                        // || !/^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,}$/.test(this.form.password)
                        if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\W_]{6,}$/.test(this.form.password)) {
                            this.$notify.error({
                                title: 'fail to submit',
                                message: 'The password must be at least 6 characters long and contain both letters and numbers.',
                                duration: 2000
                            });
                            this.isSubmitting = false;
                            return false;
                        }

                        axios.post(`${api}/insertUser`, {
                            ...this.form
                        })
                            .then((response) => {
                                this.isSubmitting = false
                                if (response.data.code == 200) {
                                    this.$notify({
                                        title: 'success',
                                        message: 'submit successfully',
                                        type: 'success'
                                    });
                                    setTimeout(() => {
                                        window.location.href = './login.html';
                                    }, 1000);
                                } else {
                                    this.$notify.error({
                                        title: 'fail to submit',
                                        message: response.data.msg,
                                        duration: 2000
                                    });
                                    errorLog('register', response.data.msg)
                                }
                            })
                            .catch((error) => {
                                this.isSubmitting = false
                                this.$notify.error({
                                    title: 'fail to submit',
                                    message: error,
                                    duration: 2000
                                });
                                errorLog('register', error)

                            });
                        // setTimeout(() => {
                        //     this.$notify({
                        //         title: '提交成功',
                        //         message: '您的科研信息已成功提交，感谢参与！',
                        //         type: 'success',
                        //         duration: 3000
                        //     });

                        //     // 在实际应用中这里会发送数据到服务器
                        //     console.log('表单数据:', this.form);

                        //     // 清空表单
                        //     this.form = {
                        //         name: '',
                        //         email: '',
                        //         organization: '',
                        //         researchField: '',
                        //         agreementAgreed: false
                        //     };
                        //     this.isSubmitting = false;
                        // }, 1500);
                    });
                },
                agreeAndClose() {
                    this.form.agreementAgreed = true;
                    this.showAgreementDialog = false;
                    this.agreementError = false;

                    this.$notify({
                        title: 'The agreement has been agreed upon.',
                        message: 'You have agreed to the terms of the agreement.',
                        type: 'success',
                        duration: 2000
                    });
                }
            }
        });
    </script>
</body>

</html>